package com.myx.typhoon.web.security;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.myx.typhoon.business.domain.User;
import com.myx.typhoon.common.enums.LoginStatus;
import com.myx.typhoon.common.util.MD5Util;
import com.myx.typhoon.web.form.LoginForm;

/**  
 * @author myx
 * @createTime 2016年2月2日 下午4:23:45  
 * 
 */
public class SecurityUtil {
	
	private static final Logger logger = LoggerFactory.getLogger(SecurityUtil.class);

	/**
	 * 用户登录
	 * @param user
	 * @return
	 */
	public static LoginStatus loginToken(LoginForm user) {
		try {
			String password = MD5Util.getMD5String(user.getPassword());
			UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(),password);
			Subject currentUser = SecurityUtils.getSubject();
			currentUser.login(token);
		}catch (UnknownAccountException e){
			return LoginStatus.UNKNOWN_ACCOUNT;
		}catch (IncorrectCredentialsException e) {
			return LoginStatus.INCORRECT_CREDENTIALS;
		}
		return LoginStatus.SUCCESS;
	}
	
	/**
	 * 获取当前登录用户信息
	 * @return
	 */
	public static User getCurrentUser() {
		try {
			Subject currentUser = SecurityUtils.getSubject();
			if(currentUser != null && currentUser.getPrincipal() != null && currentUser.isAuthenticated()) {
				return (User)currentUser.getPrincipal();
			}
		} catch (Exception e) {
			logger.error("getCurrentUser",e);
		}
		return null;
	}
	
	/**
	 * 退出当前登录用户
	 */
	public static void logutToken() {
		try {
			Subject currentUser = SecurityUtils.getSubject();
			if(currentUser != null) {
				currentUser.logout();
			}
		} catch (Exception e) {
			logger.error("logutToken error",e);
		}
	}
}
